package com.zhongdaima.netty.analysis.part0.jdk.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 欢迎关注公众号“种代码“，获取博主微信深入交流
 *
 * @author wangjianxin
 */
public class HelloNioClient {
    private static final int CLIENTS = 2;

    public static void main(String[] args) throws IOException {
        Thread client = new Thread(new Runnable() {
            final Selector selector = Selector.open();
            final SocketChannel[] clients = new SocketChannel[CLIENTS];

            @Override
            public void run() {
                //创建两个客户端
                for (int i = 0; i < CLIENTS; i++) {
                    try {
                        //连接8000端口
                        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(8000));
                        //将channel设置为非阻塞的
                        socketChannel.configureBlocking(false);
                        //注册到selector
                        socketChannel.register(this.selector, SelectionKey.OP_READ, socketChannel);
                        //保存channel
                        clients[i] = socketChannel;
                    }catch (Throwable e){

                    }
                }
                for (int i = 0; i < Integer.MAX_VALUE; i++) {
                    try {
                        //向服务端发送“zhongdaima" + 客户端编号
                        for (int j = 0; j < clients.length; j++) {
                            this.clients[j].write(ByteBuffer.wrap(("zhongdaima" + j).getBytes()));
                        }
                        //监视Channel是否有可读事件发生
                        if (this.selector.select() > 0) {
                            Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                            Iterator<SelectionKey> iterator = selectionKeys.iterator();
                            while (iterator.hasNext()){
                                SelectionKey key = iterator.next();
                                try {
                                    SocketChannel channel = (SocketChannel) key.attachment();
                                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                                    int read = channel.read(buffer);
                                    buffer.flip();
                                    //打印服务端返回数据
                                    System.out.println(new String(buffer.array(), 0, read));
                                }finally {
                                    iterator.remove();
                                }
                            }
                        }
                        Thread.sleep(1000);
                    }catch (Throwable e){

                    }
                }
            }
        });
        client.start();

    }
}
